import java.util.*;

public class Solution675 {
    public int cutOffTree(List<List<Integer>> forest) {
        List<int[]> target=new ArrayList<>();
        for (int i=0;i<forest.size();i++){
            for (int j=0;j<forest.get(i).size();j++){
                if (forest.get(i).get(j)>=2){
                    target.add(new int[]{i,j,forest.get(i).get(j)});
                }
            }
        }
        target.sort(Comparator.comparingInt(a -> a[2]));
        int ans=0;
        int[] cur={0,0};
        for (int[] ints : target) {
            int[] t = {ints[0], ints[1]};
            int p = dis(forest, cur, t);
            if (p == -1) {
                return -1;
            }
            cur = t;
            ans += p;
        }
        return ans;
    }

    private int dis(List<List<Integer>> forest, int[] cur, int[] target) {
        Queue<int[]> queue=new LinkedList<>();
        int[] dx={1,0,-1,0};
        int[] dy={0,1,0,-1};
        int[][] visit=new int[forest.size()][forest.get(0).size()];
        for (int[] ints : visit) {
            Arrays.fill(ints,-1);
        }
        visit[cur[0]][cur[1]]=0;
        queue.offer(new int[]{cur[0],cur[1]});
        while (!queue.isEmpty()){
            int[] p=queue.poll();
            if (target[0]==p[0] && target[1]==p[1]){
                return visit[p[0]][p[1]];
            }
            for (int i=0;i<4;i++){
                int x=p[0]+dx[i];
                int y=p[1]+dy[i];
                if (x>=0 && x<forest.size() && y>=0 && y<forest.get(0).size() && visit[x][y]==-1 && forest.get(x).get(y)!=0){
                    visit[x][y]=visit[p[0]][p[1]]+1;
                    queue.offer(new int[]{x,y});
                }
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(new Solution675().cutOffTree(Arrays.asList(Arrays.asList(1,2,3),Arrays.asList(0,0,4),Arrays.asList(7,6,5))));
    }
}
